package cn.wolfcode.shop.cloud.resolver;

import cn.wolfcode.shop.cloud.anno.ValidationAnno;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.redis.RedisService;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import cn.wolfcode.shop.cloud.util.MemberkeyPrefix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType()==User.class && methodParameter.hasParameterAnnotation(ValidationAnno.class);
    }

    //第一个方法为true的话，执行下面该方法
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取request对象
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        //获取token
        String userToken = CookieUtil.getToken("userToken", request);
        //判断userToken是否为空
        if(userToken!=null){
            //从redis中获取当前用户登录对象,并返回
            return redisService.get(MemberkeyPrefix.USER_TOKEN, userToken,User.class);
        }
        return null;
    }
}
